<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2022/8/31
 * Time: 14:18
 */

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Tools\FunTool;

class Pay
{
    /**
     * 获取支付列表
     * @param int $discount
     * @return array
     */
    public function getRuleList($discount = 0, $channelId = 'default', $vip = [0], $version = "1.0.0") {
        if (version_compare($version,  env('NEW_VERSION')) >= 0) {
            if (version_compare($version,  '1.4.0') >= 0 && version_compare($version, '1.5.0') < 0) {
                $ruleArr = DB::table('pay_rule')->where(['discount'=>$discount])->where('id', '>=', 142)->where('id', '<=', 154)->get()->toArray();
            } else {
                $ruleIds = [155,156];
                //添加终生会员商品
                if (version_compare($version,"1.7.4") >= 0) {
                    $ruleIds = [155,156,160];
                }
                $ruleArr = DB::table('pay_rule')->where(['discount'=>$discount])->whereIn("id",$ruleIds)->get()->toArray();
            }
        } else {
            $ruleArr = DB::table('pay_rule')->where(['discount'=>$discount])->where('id', '<', 142)->get()->toArray();    
        }
        if ($ruleArr[0] ?? false) {
            return json_decode(json_encode($ruleArr), true);
        }
        return null;
    }

    public function getRule($id) {
        $rule = DB::table('pay_rule')->where(['id'=>$id])->first();
        if ($rule ?? false) {
            return (array)$rule;
        }
        return null;
    }

    public function getRuleByDrawingId($drawingId) {
        $rule = DB::table('pay_rule')->where(['drawing_id' => $drawingId])->orderBy("id", "desc")->get()->toArray();
        if ($rule[0] ?? false) {
            return json_decode(json_encode($rule), true);
        }
        return null;
    }

    //获取永久信息
    public function getRuleBypermanent() {
        $rule = DB::table('pay_rule')->where(['type' => 0])->get()->toArray();
        if ($rule[0] ?? false) {
            return (array)$rule[0];
        }
        return null;
    }

    public function makeOrderId()
    {
        return date('ymdhis') . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    public function insertOrder($ruleId, $price, $type, $len, $dot, $payType, $userId, $deviceId, $accountName, $ecyLen, $googleIsSubscribe = 0, $drawingId = 0, $isGold = 0, $googleId = "", $version = "", $platform = "") {
        $orderId =  $this->makeOrderId();
        $rule_info = DB::table('pay_rule')->where('id',$ruleId)->first();
        DB::table('pay_order')->insertGetId([
            'order_id' => $orderId,
            'type' => $type,
            'price' => $price,
            'len' => $len,
            'ecy_len' => $ecyLen,
            'dot' => $dot,
            'status' => 0,
            'rule_id' => $ruleId,
            'pay_type' => $payType,
            'user_id' => $userId,
            'device_id' => $deviceId,
            'account_name' => $accountName,
            'google_is_subscribe' => $googleIsSubscribe,
            'drawing_id' => $drawingId,
            'is_gold' => $isGold,
            'google_id' => $googleId,
            'version' => $version,
            'platform' => $platform,
            'label'=> $rule_info ? $rule_info->category : 0,
            'created_at'=>FunTool::getReduceTime(4)
        ]);
        return $orderId;
    }

    public function createOrder(array $insertData) {
        $id = DB::table('pay_order')->insertGetId($insertData);
        return $id;
    }

    public function getOrder($orderId) {
        $orderInfo = DB::table('pay_order')->where(['order_id'=>$orderId])->first();
        if (!$orderInfo) {
            return null;
        }
        return (array)$orderInfo;
    }

    public function getOrderWithExternalOrderId($externalOrderId) {
        $orderInfo = DB::table('pay_order')->where(['external_order_id'=>$externalOrderId])->first();
        if (!$orderInfo) {
            return null;
        }
        return (array)$orderInfo;
    }

    public function getOrderTransactionOrderIdByApple($transaction_order_id,$good_id) {
        $orderInfo = DB::table('pay_order')->where(["google_id" => $good_id,"transaction_order_id" => $transaction_order_id])->orderByDesc("id")->first();
        if (!$orderInfo) {
            return null;
        }
        return (array)$orderInfo;
    }

    public function getOrderTransactionOrderId($transaction_order_id) {
        $orderInfo = DB::table('pay_order')->where(['transaction_order_id'=>$transaction_order_id])->first();
        if (!$orderInfo) {
            return null;
        }
        return (array)$orderInfo;
    }

    public function updatePay($id, $externalOrderId,$transaction_order_id = "") {
        return DB::table('pay_order')->where(['id'=>$id])->update(['status'=>1,'pay_at'=>FunTool::getReduceTime(4),'external_order_id'=>$externalOrderId,"transaction_order_id" => $transaction_order_id]);
    }

    public function newUpdatePay($id, $updateFiled) {
        $updateFiled = array_merge($updateFiled,['status'=>1,'pay_at'=>FunTool::getReduceTime(4)]);
        return DB::table('pay_order')->where(['id'=>$id])->update($updateFiled);
    }

    public function updatePayById($id,$updateData) {
        return DB::table('pay_order')->where(['id'=>$id])->update($updateData);
    }

    public function getFirst($userId) {
        $data = DB::table('pay_order')->where(['user_id'=> $userId, 'status' => 1])->first();
        if (!$data) {
            return null;
        }
        return (array)$data;
    }

    public function getFirstInfo($where){
        $data = DB::table('pay_order')->where($where)->first();
        if (!$data) {
            return null;
        }
        return (array)$data;
    }

    public function deletePayById($id){
        $result = DB::table('pay_order')->where('id',$id)->delete();
        return $result;
    }

    // 获取支付次数
    public function getUserCount($userId) {
        $count = DB::table('pay_order')->where(['user_id'=> $userId, 'status' => 1])->count();
        return $count;
    }

    // 获取支付次数
    public function getDeviceIdCount($deviceId,$platform) {
        $count = DB::table('pay_order')->where(['device_id'=> $deviceId, 'platform' => $platform, 'status' => 1])->count();
        return $count;
    }

	// 获取是否支付过
	public function getDevicePaidBuyDeviceID($sDeviceID) {
		$aData = DB::table('pay_order')->where(['device_id'=> $sDeviceID, 'status' => 1])->first();
		return !empty($aData);
	}
	public function getDevicePaidByUserID($iUserId) {
		$aData = DB::table('pay_order')->where(['user_id'=> $iUserId, 'status' => 1])->first();
		return !empty($aData);
	}

    // 设置只上传一次
    public function incInOrder($deviceId) {
        $key = 'PAY:INODER:' . $deviceId;
        $ret = Redis::INCR($key);
        Redis::EXPIRE($key, 3600*24*30);
        return $ret;
    }


    // 是否命中头条屏蔽机型
    public function hasModelBlock($model) {
        $key = 'taoutiao:model:block';
        return Redis::HEXISTS($key, $model);
    }

    // 获取非点数支付次数
    public function getUserCountNoDot($userId) {
        $count = DB::table('pay_order')->where([
            ['user_id', '=', $userId],
            ['status', '=', 1],
            ['rule_id', '!=', 147]
        ])->count();
        return $count;
    }

    //获取永久信息
    public function getNewVersionData() {
        $rule = DB::table('pay_rule')->where('id', '>=', 142)->where('id', '<=', 154)->get()->toArray();
        
        if ($rule[0] ?? false) {
            return json_decode(json_encode($rule), true);
        }
        return null;
    }

    //获取点数规则
    public function getDotRules($id) {
        $rule = DB::table('pay_rule')->where('id', '=', $id)->get()->toArray();
        
        if ($rule[0] ?? false) {
            return json_decode(json_encode($rule), true);
        }
        return null;
    }

    public function updatePayData($oldUserId, $newUserId) {
        return DB::table('pay_order')->where(['user_id'=>$oldUserId])->update(['user_id'=>$newUserId]);
    }

    public function getIsPay($userId, $deviceId){

        $amount = 0;

        if ($userId > 0) {
            $amount = DB::table('pay_order')->where(['status'=>1, 'user_id'=>$userId])->count();
        }else{
            $amount = DB::table('pay_order')->where(['status'=>1, 'device_id'=>$deviceId])->count();
        }
        
        return $amount > 0 ? true : false;

    }

    /**
     * 是否购买过会员
     */
    public function getIsPayVip($userId, $deviceId){

        $isPayVip = false;

        if ($userId > 0) {
            $amount = DB::table('pay_order')->where('user_id',$userId)->where('status',1)->whereIn('label',[2,3,4])->count();
            if ($amount > 0) {
                $isPayVip = true;
            }
        }else{
            $amount = DB::table('pay_order')->where('device_id',$deviceId)->where('status',1)->whereIn('label',[2,3,4])->count();
            if ($amount > 0) {
                $isPayVip = true;
            }
        }        
        Log::info('getIsPayVip-'.$userId.'-'.$deviceId, [$isPayVip]);
        return $isPayVip;

    }

    /**
     * 付款前置，根据deviceId，将userId=0的用户进行绑定
     * @param $deviceId
     * @param $userId
     * @return void
     */
    public function updateUserIdByDeviceId($deviceId,$userId,$platform) {

        $user = new User();
        $userDrawing = new UserDrawing();
        $user->updateNoLoginData($deviceId, $userId, $platform);

        DB::beginTransaction();
        Log::info("updateUserIdByDeviceId :",["device_id" => $deviceId,"user_id" => $userId,"platform" => $platform]);
        try {
            //查到需要修改的数据
            $list = DB::table("pay_order")
                ->where(["device_id" => $deviceId,"user_id" => 0,"platform" => $platform])
                ->get(["id","len","ecy_len","dot","is_gold","drawing_id","status","is_try","google_id"])->toArray();
            //Log::info("updateUserIdByDeviceId list : ",["list" => $list]);
            if (empty($list)) {
                throw new \Exception("暂无需要更新的订单");
            }
            //需要更新的订单
            $orderIds = [];
            //会员过期时间
            $allVipExp = 0;
            //点
            $allDot = 0;
            //设置充值赠送点数动画值
            $allDhNum = 0;
            // 是否终生会员
            $isSuperVip = false;
            foreach ($list as $item) {
                $item = (array)$item;
                $len = $item['len'];
                $isAddUserVip = false;

                //status = 1 已扣款
                if ($item["status"] == 1) {
                    $isAddUserVip = true;
                    //终生用户
                    if (in_array($item["google_id"], config('app.pay_lifetime'))) {
                        $isSuperVip = true;
                    }
                }

                //(status = 0 and is_try = 1)订阅试用状态已回传，但未付款，赠送用户三天试用时间
                if ($item["status"] == 0 && $item["is_try"] == 1) {
                    $len = 3;
                    $isAddUserVip = true;
                }

                if (!$isAddUserVip) {
                    continue;
                }

                $orderIds[] = $item["id"];
                //$len = $item['len'];
                //dot
                $allDot += $item["dot"];
                //allVipExp
                if ($len > 0 && $len != 36500) {
                    $allVipExp += $len * 24 * 3600;
                }
                //IOS
                if ($platform == 1) {
                    if($item["len"] > 0 && $item["len"] != 36500) {
                        if ($item["is_gold"] == 1) { //黄金会员
                        } else { //普通会员
                            $times = $len * 24 * 3600;
                            Log::info(sprintf("苹果普通会员更新 DrawExp. user_id : %s, drawing_id : %s, times : %s.",$userId,$item['drawing_id'],$times));
                            $userDrawing->updateUserDrawExp($userId, $item['drawing_id'], $times);
                        }
                    }
                }
                //dhNum
                if ($item["dot"] > 0) {
                    $allDhNum += $item["dot"];
                }
            }

            //订单更新
            if (!empty($orderIds)) {
                Log::info("需要更新的订单ID:",["ids" => $orderIds,"user_id" => $userId]);
                DB::table("pay_order")->whereIn("id" , $orderIds)->update(["user_id" => $userId]);
            }

            //更新会员过期时间
            if ($allVipExp > 0) {
                Log::info("更新会员过期时间:",["user_id" => $userId,"all_vip_exp" => $allVipExp]);
                $user->updateVipExp($userId, $allVipExp, 'vip_exp');
            }
            //更新用户点数
            if ($allDot > 0) {
                Log::info("更新用户点数:",["user_id" => $userId,"allDot" => $allDot]);
                $user->updateDot($userId, $allDot, 4);
            }
            //更新充值赠送动画值
            if ($allDhNum > 0) {
                Log::info("更新充值赠送动画值:",["user_id" => $userId,"allDhNum" => $allDhNum]);
                $user->setDhNum($userId, $allDhNum);
            }
            //标记用户为终生用户
            if ($isSuperVip) {
                Log::info("标记用户为终生用户:",["user_id" => $userId]);
                $user->updateById($userId, ["is_super_vip" => 1]);
            }
            
            DB::commit();
        } catch (\Exception $e) {
            Log::warning("updateUserIdByDeviceId error :",["device_id" => $deviceId,"user_id" => $userId,"platform" => $platform,"error" => $e->getMessage(),"line" => $e->getLine()]);
            DB::rollBack();
        }

        //更新适用的信息
        (new UserOntrial())->updateUserIdByDeviceId($deviceId,$userId);
    }

    public function getNumByAppleTrade($where) {
        return DB::table("pay_order")->where($where)->count();
    }

    public function getGuideRule() {
        $rule = DB::table('pay_rule')->where(['id'=> env('GUIDE_PAY_RULE_ID')])->first();
        if ($rule ?? false) {
            return [
                'id' => $rule->id,
                "apple_order_id" => $rule->apple_order_id,
                "google_order_id" => $rule->google_order_id,
            ];
        }
        return [];
    }

    /**
     * google退费处理用户信息 //3取消订阅,12撤销订阅，13已过期 ,8价格变动
     */
    public function googlePayRefund($orderId ,$refundData = [], $notifyType){

        $orderInfo = $this->getOrder($orderId);
        if (empty($orderInfo)) {
            Log::info("googlePayRefund :",["msg"=>'未找到订单信息',"order_id" => $orderId]);
            return ['code'=>500, 'msg'=>'未找到订单信息'];
        }
        if ($orderInfo['user_id'] <= 0) {
            Log::info("googlePayRefund :",["msg"=>'未找到用户信息1',"order_id" => $orderId]);
            return ['code'=>500, 'msg'=>'未找到用户信息1'];
        }
        $userInfo = DB::table('user')->where('id',$orderInfo['user_id'])->first();
        if (empty($userInfo)) {
            Log::info("googlePayRefund :",["msg"=>'未找到用户信息2',"order_id" => $orderId]);
            return ['code'=>500, 'msg'=>'未找到用户信息2'];
        }
        $userInfo = (array)$userInfo;
        $updateArr = [];
        if ($orderInfo['google_id'] == 'lifetime_pro') {//永久会员，需要撤销用户的会员标识
            if ($orderInfo['user_id'] > 0) {
                $updateArr['is_super_vip'] = 0;
            }
        }
        //是购买的会员，减去会员天数
        if ($orderInfo['len'] > 0) {
            $reduce_time = $orderInfo['len'] * 86400;
            $lost = $userInfo['vip_exp'] - $reduce_time;
            $vip_exp =  $lost > 0 ? $lost : 0;
            if ($vip_exp > 0) {
                $updateArr['vip_exp'] = $vip_exp;
            }
        }
        if ($orderInfo['ecy_len'] > 0) {
            $reduce_time = $orderInfo['ecy_len'] * 86400;
            $lost = $userInfo['rcy_vip_exp'] - $reduce_time;
            $vip_exp =  $lost > 0 ? $lost : 0;
            if ($vip_exp > 0) {
                $updateArr['rcy_vip_exp'] = $vip_exp;
            }
        }
        //有点数，减去点数
        $dot = $userInfo['dot'] - $orderInfo['dot'];
        $dot = $dot > 0 ? $dot : 0;
        if ($dot > 0) {
            $updateArr['dot'] = $dot;
        }
        if (!empty($updateArr) && $notifyType == 12) {//退款的才进行处理
            DB::table('user')->where('id',$userInfo['id'])->update($updateArr);
        }
        $extend = $orderInfo['extend'];
        $extendUpdate = empty($extend) ? [] : json_decode($extend, true);
        if (!empty($refundData)) {
            $extendUpdate['refundData'] = $refundData;
            DB::table('pay_order')->where('id',$orderInfo['id'])->update(['extend'=>json_encode($extendUpdate)]);
        }
        if ($notifyType == 12) {//订单状态改成已退款
            $refundTime = FunTool::getReduceTime();
            DB::table('pay_order')->where('id',$orderInfo['id'])->update(['status'=>2,'refund_time'=>$refundTime]);
        }
        
        Log::warning("googlePayRefund :",["order_id" => $orderId,"user_id" => $userInfo['id'], 'data'=>$updateArr]);
        return ['code'=>200, 'msg'=>'成功'];

    }


    public function getRuleDiscount(){

        return DB::table('pay_rule')->whereIn('id',[161,162])->select('id','name','price','apple_order_id','apple_original_order_id','ios_is_subscribe','google_order_id','member_desc','google_is_subscribe','google_original_order_id')->get()->toArray();

    }



}